package com.atguigu.srb.mybatisPlus;

import com.atguigu.srb.mybatisPlus.mapper.UserMapper;
import com.atguigu.srb.mybatisPlus.pojo.entity.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

@SpringBootTest
public class mybatisQwrapper {

    @Resource
    UserMapper userMapper;

    @Test
    public void testWrapper() {
        //查询名字中包含n，年龄大于等于10且小于等于20，email不为空的用户
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like("name","n")
                .between("age",10,20)
                .isNotNull("email");
        userMapper.selectList(userQueryWrapper);
    }


    @Test
    public void testWrapper2(){
        //按年龄降序查询用户，如果年龄相同则按id降序排列
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.orderByDesc("age").orderByDesc("id");
        userMapper.selectList(userQueryWrapper);
    }

    @Test
    public void deleteUserByEmail(){
        //删除email为空的用户
        QueryWrapper<User> email = new QueryWrapper<User>().isNull("email");
        userMapper.delete(email);
    }

    @Test
    public void test04(){
        //查询名字中包含n，且（年龄小于18或email为空的用户）
        //并将这些用户的年龄设置为18，邮箱设置为 user@atguigu.com
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like("name","n")
                .and(i -> i.lt("age",18).or().isNull("email"));
        userMapper.selectList(userQueryWrapper);
        User user = new User();
        user.setAge(18);
        user.setEmail("user@atguigu.com");
        userMapper.update(user,userQueryWrapper);
    }

    @Test
    public void test05(){
        //指定字段，查询所有用户的用户名和年龄
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.select("name","age");
        userMapper.selectList(userQueryWrapper);
    }

    @Test
    public void updateUser(){
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.set("age",18).set("email","user@atguigu.com")
                .like("name","n")
                .and(i -> i.lt("age",18).or().isNull("email"));
        userMapper.update(null,userUpdateWrapper);
    }

}
